// 用于实现组件的懒加载
import { useIntersectionObserver, useIntervalFn } from '@vueuse/core'
import { ref, onUnmounted } from 'vue'
import dayjs from 'dayjs'

export const useLazyData = (apiFn) => {
  const target = ref(null)
  const result = ref([])

  const { stop } = useIntersectionObserver(
    // 被监视的dom
    target,
    ([{ isIntersecting }], observerElement) => {
      if (isIntersecting) {
        stop()

        // 调用api获取数据
        apiFn().then(data => {
          result.value = data.result
        })
      }
    }, {
      threshold: 0
    }
  )

  return { target, result }
}

// 封装支付页面的倒计时效果
export const usePayTime = () => {
  const time = ref(0)

  const timeText = ref('')

  const { resume, pause } = useIntervalFn(() => {
    time.value--
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')

    if (time.value < 0) {
      pause()
    }
  }, 1000, false)

  const start = (countDown) => {
    time.value = countDown
    timeText.value = dayjs.unix(time.value).format('mm分ss秒')
    resume()
  }

  onUnmounted(() => {
    pause()
  })

  return {
    timeText,
    start
  }
}
